package com.czl.module_service.fragment.purchase

import android.os.Handler
import android.os.Looper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.event.LiveBusCenter
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.PurchaseApplyAdapter
import com.czl.module_service.databinding.FragmentPurchaseMyApplyBinding
import com.czl.module_service.extension.loadCompletedData
import com.czl.module_service.viewmodel.PurchaseMyApplyViewModel

@Route(path = AppConstants.Router.Service.F_SERVICE_PURCHASE_MY_APPLY)
class PurchaseMyApplyFragment :
    BaseFragment<FragmentPurchaseMyApplyBinding, PurchaseMyApplyViewModel>() {

    private lateinit var mAdapter: PurchaseApplyAdapter
    /*private val mAdapter: PurchaseApplyAdapter by lazy {
        PurchaseApplyAdapter(this).apply {

        }
    }*/

    private var loaded: Boolean = false
    override fun initContentView(): Int {
        return R.layout.fragment_purchase_my_apply
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        super.initData()
        viewModel.tabIndex =
            arguments?.getSerializable(AppConstants.BundleKey.USAGE_TAB_INDEX) as Int
        initAdapter()
    }

    override fun onResume() {
        super.onResume()
        loadData()
    }

    private fun loadData() {
        if (!loaded) {
            reload()
        }
    }

    override fun useBaseLayout(): Boolean {
        return false
    }

    private fun initAdapter() {
        mAdapter = PurchaseApplyAdapter(this).apply {
        }
        binding.ryCommon.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = mAdapter
        }
        mAdapter.tabIndex = viewModel.tabIndex!!
    }

    override fun initViewObservable() {
        LiveBusCenter.observeAssetResultReturnEvent(this, {
            /*if (viewModel.tabIndex == 1) {
                reload()
            }*/
            Handler(Looper.myLooper()!!).postDelayed(object : Runnable {
                override fun run() {
                    reload()
                }
            }, 1000)
        })
        viewModel.uc.loadCompleteEvent.observe(this, { data ->
            this.loadCompletedData(
                data?.hasNextPage,
                viewModel.currentPage == 2,
                data != null,
                data?.total,
                data?.list,
                mAdapter,
                binding.ryCommon,
                binding.smartCommon
            )
        })
        viewModel.uc.loadFinallyEvent.observe(this, {
            loaded = true
        })
    }

    override fun reload() {
        super.reload()
        binding.smartCommon.autoRefresh()
    }
}